package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.constant.REnum;
import cn.edu.ctbu.dp01.dao.StudentRepository;
import cn.edu.ctbu.dp01.entity.Student;
import cn.edu.ctbu.dp01.exception.RException;
import org.hibernate.query.derived.AnonymousTupleEntityValuedModelPart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {

    @Autowired
    public StudentRepository studentRepository;

    /**
     * 读所有学生列表
     *
     * @return List Student
     */
    public List<Student> findAll() {

        return studentRepository.findAll();
    }

    /**
     * 按id进行查询
     *
     * @param id 主键，整数
     * @return
     */
    public Student findById(Integer id) {

        return studentRepository.findById(id).get();
    }


    /**
     * 按名字查询，Like
     *
     * @return
     * @parame id 主键， 整数
     */


    public List<Student> findByNameLike(String name) {
        return studentRepository.findByNameLike(name);
    }

    /**
     * 按名字和密码查询
     *
     * @param password
     * @return
     * @parame name
     */
    public List<Student> findByNameAndPassword(String name, String password) {

        return studentRepository.findByNameAndPassword(name, password);
    }


    public void Insert(Student student) {
        studentRepository.save(student);
    }

//    public void Update(Student student){
//        studentRepository.save(student);
//    }
//
//    public void delete(Integer id){
//        studentRepository.deleteById(id);
//    }

    /**
     * 新增学生
     *
     * @param student
     * @return
     */
    public Student add(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 更新学生
     *
     * @param student
     * @return
     */
    public Student upde(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 删除学生
     *
     * @param id
     * @return
     */
    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }

    public Student validateUsernameAndPassword(String sno, String password) throws Exception {

        List<Student> students=studentRepository.findBySno(sno);
        if(students.size() > 0){
            //可能对password加密，但我们暂时不做处理
            Student student=students.get(0);
            if(student.getPassword().equals(password)){
                //成功
                return student;
            }else{
                throw new RException(REnum.LOGIN_ERR);
            }
        }else{
            throw new RException(REnum.LOGIN_ERR);
        }
    }
}
